import { createRouter, createWebHistory } from 'vue-router';
import LoginX from "@/views/common/LoginX.vue";
import Main from "@/views/common/Main.vue";
import {useUserStore} from "@/store/settings.js";




// 定义路由规则
const routes = [
  {
    path: '/',
    name: 'LoginX',
    component: LoginX,
    meta: { title: "登录", isLogin: false }, // 登录页无需登录校验
  },
  {
    path: '/main',
    name: 'Main',
    component: Main,
    meta: { title: "工作台", isLogin: true }, // 主页面需要登录校验
    children: [
      { path: 'home', name: 'Home', component: () => import('@/views/Home.vue'), meta: { title: "工作台", isLogin: true } },
      { path: '', name: 'First', component: () => import('@/views/FirstPage.vue'), meta: { title: "首页", isLogin: true } },
      { path: 'disciplinary-management', name: 'DisciplinaryManagement', component: () => import('@/views/DisciplinaryManagement.vue'), meta: { title: "违纪管理", isLogin: true } },
      // { path: 'statistics', name: 'Statistics', component: () => import('@/views/Statistics.vue'), meta: { title: "全校处分统计", isLogin: true } },
      { path: 'journal', name: 'journal', component: () => import('@/views/Journal.vue'), meta: { title: "日志记录", isLogin: true } },
      { path: 'user-list', name: 'UserList', component: () => import('@/views/UserList.vue'), meta: { title: "用户列表", isLogin: true } },
      { path: 'role-management', name: 'RoleManagement', component: () => import('@/views/RoleManagement.vue'), meta: { title: "角色管理", isLogin: true } },
      // { path: 'organization-management', name: 'OrganizationManagement', component: () => import('@/views/OrganizationManagement.vue'), meta: { title: "组织管理", isLogin: true } },
      { path: 'api-docs', name: 'ApiDocs', component: () => import('@/views/ApiDocs.vue'), meta: { title: "API文档", isLogin: true } },
    ],
  },
];



// 创建路由实例
const router = createRouter({
  history: createWebHistory(), // 使用 HTML5 的 history 模式
  routes, // 注册路由规则
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const isAuthenticated = !!userStore.getUser.token; // 判断用户是否已登录

  if (to.meta.isLogin && !isAuthenticated) {
    // 需要登录的页面且未登录时跳转到登录页
    // ElMessage.warning('请先登录');
    next({ name: 'LoginX', query: { redirect: to.fullPath } });
  } else {
    // 设置动态标题
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    next(); // 继续导航
  }
});


export default router;
